﻿using System;
using System.Reflection;
using System.Runtime.Remoting;

namespace Ooaavee.Scripting.Remoting
{
    /// <summary>
    /// Factory class to create objects exposing IRemoteScript interface.
    /// </summary>
    internal sealed class RemoteScriptFactory : MarshalByRefObject
    {
        /// <summary>
        /// Factory method to create an instance of the type whose name is specified, using the named assembly file and the 
        /// constructor that best matches the specified parameters. 
        /// </summary>
        /// <param name="assemblyFile">The name of a file that contains an assembly where the type named typeName is sought.</param>
        /// <param name="typeName">The name of the preferred type.</param>
        /// <param name="constructArgs">An array of arguments that match in number, order, and type the parameters of the constructor to invoke, or null for default constructor.</param>
        /// <returns>The return value is the created object represented as ILiveInterface.</returns>
        internal IRemoteScript CreateRemoteScript(string assemblyFile, string typeName, object[] constructArgs)
        {          
            ObjectHandle handle = Activator.CreateInstanceFrom(
                assemblyFile,
                typeName,
                false,
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance,
                null,
                constructArgs,
                null,
                null);

            IRemoteScript remoteScript = (IRemoteScript)handle.Unwrap();

            return remoteScript;
        }
    }
}
